import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;

/**
 * 542. 01 矩阵
 * https://leetcode.cn/problems/01-matrix/description/
 */
class Solution {
    int m, n;
    int[] dx = {-1, 1, 0, 0};
    int[] dy = {0, 0, -1, 1};
    public int[][] updateMatrix(int[][] mat) {
        m = mat.length; n = mat[0].length;
        int[][] dist = new int[m][n];
        //dist数组全初始化为-1
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                dist[i][j] = -1;
            }
        }
        Queue<int[]> q = new LinkedList<>();
        //先把坐标的值是0的位置加入队列, 把是 0 的值夜添加进dist中
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(mat[i][j] == 0) {
                    dist[i][j] = 0;
                    q.add(new int[]{i, j});
                }
            }
        }
        //新加入队列的就是"超级源点",从它出发，每bfs一步，就+1
        while(!q.isEmpty()) {
            int[] tmp = q.poll();
            int a = tmp[0], b = tmp[1];
            for(int i = 0; i < 4; i++) {
                int x = a + dx[i], y = b + dy[i];
                if(x >= 0 && x < m && y >= 0 && y < n && dist[x][y] == -1) {
                    dist[x][y] = dist[a][b] + 1;
                    q.add(new int[]{x, y});

                }
            }
        }

        return dist;
    }
}